from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
import stripe
import os
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 初始化 FastAPI 应用
app = FastAPI(title="Stripe Webhook Handler")

# 配置 Stripe 密钥（建议从环境变量获取）
STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY", "你的测试密钥")
STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET", "你的Webhook签名密钥")

# 设置 Stripe API 密钥
stripe.api_key = STRIPE_SECRET_KEY


# 事件处理函数
async def handle_payment_success(event: stripe.Event):
    """处理支付成功事件"""
    payment_intent = event.data.object
    logger.info(
        f"支付成功 - 客户: {payment_intent.customer}, "
        f"金额: {payment_intent.amount / 100} {payment_intent.currency}"
    )
    # 在这里添加业务逻辑：更新订单状态、发送确认邮件等
    # 例如：await update_order_status(payment_intent.metadata.order_id, "paid")


async def handle_subscription_created(event: stripe.Event):
    """处理订阅创建事件"""
    subscription = event.data.object
    logger.info(
        f"订阅创建 - 客户: {subscription.customer}, "
        f"订阅ID: {subscription.id}, "
        f"计划: {subscription.items.data[0].plan.id}"
    )
    # 在这里添加业务逻辑：开通会员权限等


async def handle_subscription_failed(event: stripe.Event):
    """处理订阅付款失败事件"""
    subscription = event.data.object
    logger.info(
        f"订阅付款失败 - 客户: {subscription.customer}, "
        f"订阅ID: {subscription.id}"
    )
    # 在这里添加业务逻辑：发送付款失败提醒等


# Webhook 端点
@app.post("/stripe-webhook")
async def stripe_webhook(request: Request):
    # 获取请求体和签名头
    payload = await request.body()
    sig_header = request.headers.get("Stripe-Signature")

    if not sig_header:
        raise HTTPException(status_code=400, detail="缺少 Stripe-Signature 头")

    try:
        # 验证 Webhook 签名
        event = stripe.Webhook.construct_event(
            payload=payload,
            sig_header=sig_header,
            secret=STRIPE_WEBHOOK_SECRET
        )
    except ValueError as e:
        # 无效的请求体
        logger.error(f"无效的请求体: {str(e)}")
        raise HTTPException(status_code=400, detail="无效的请求体")
    except stripe.error.SignatureVerificationError as e:
        # 签名验证失败
        logger.error(f"签名验证失败: {str(e)}")
        raise HTTPException(status_code=400, detail="无效的签名")

    # 处理事件
    event_type = event.type
    logger.info(f"收到 Stripe 事件: {event_type}")

    # 根据事件类型分发处理
    event_handlers = {
        "payment_intent.succeeded": handle_payment_success,
        "subscription.created": handle_subscription_created,
        "subscription.payment_failed": handle_subscription_failed
        # 可以添加更多事件类型
    }

    if event_type in event_handlers:
        await event_handlers[event_type](event)
    else:
        logger.info(f"未处理的事件类型: {event_type}")

    # 返回成功响应给 Stripe
    return JSONResponse(content={"received": True})


if __name__ == "__main__":
    import uvicorn

    # 生产环境应使用 HTTPS 并配置合适的参数
    uvicorn.run(app, host="0.0.0.0", port=8000)
